import { FC, useEffect, lazy, PropsWithChildren } from 'react'
import { RouteComponentProps } from 'react-router'
import { observer } from 'mobx-react'
import { Layout, Spin } from 'antd'
import { useStore } from '@/store'
import useUserInfo from '@/hooks/user'
import { getUrlByLevel } from '@/utils/urlUtil'

const AppHeader = lazy(() => import('./Header'))
const AppContent = lazy(() => import('./Content'))
const AppSider = lazy(() => import('./Sider'))

const AppLayout: FC<RouteComponentProps> = (props: PropsWithChildren<RouteComponentProps>) => {
  const { userData, loading } = useUserInfo()
  const { userStore, appStore } = useStore()

  const setUserStore = () => {
    userStore.getUserData(userData)
  }
  useEffect(() => {
    setUserStore()
    // eslint-disable-next-line
  }, [userData])
  const { location } = props
  const parentCode = getUrlByLevel(location.pathname, 1)
  const childCode = getUrlByLevel(location.pathname, 2)
  // 初始化选中
  useEffect(() => {
    appStore.setDefaultSiderSelect([childCode])
    // eslint-disable-next-line
  }, [childCode])
  const layoutCenter = () => {
    if (parentCode && childCode) {
      return (
        <Layout>
          <AppSider parentCode={parentCode} />
          <AppContent />
        </Layout>
      )
    }
    return (
      <Layout>
        <AppContent />
      </Layout>
    )
  }

  const appBody = () => {
    if (loading) return <Spin />
    return (
      <div>
        <AppHeader />
        {
          layoutCenter()
        }
      </div>)
  }
  return (
    <Layout style={{ height: '100vh', overflow: 'auto' }}>
      {
        appBody()
      }
    </Layout>
  )
}
export default observer(AppLayout)
